package com.salesmanager.web.services.controller.category;

import com.salesmanager.core.business.category.model.Category;
import com.salesmanager.core.business.category.service.CategoryService;
import com.salesmanager.core.business.category.model.CategoryCriteria;
import com.salesmanager.web.entity.catalog.category.CategorySimpleTreeNode;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Liutong on 2016/6/7.
 */
@Controller
@RequestMapping("/services")
public class CategoryRESTController {

    private static final Logger LOGGER = LoggerFactory.getLogger(CategoryRESTController.class);

    @Autowired
    private CategoryService categoryService;
    /**
     * 获得分类树
     * 管理员获得所有分类
     * @return
     */
    @RequestMapping(value = "/private/category/all",method = RequestMethod.GET)
    @ResponseBody
    public List<CategorySimpleTreeNode> getAllWithAdmin(){
        CategoryCriteria criteria = new CategoryCriteria();
        return this.queryCategory(criteria);
    }

    private List<CategorySimpleTreeNode> queryCategory(CategoryCriteria criteria){
        Map<Long,CategorySimpleTreeNode> nodeMap = new LinkedHashMap<Long, CategorySimpleTreeNode>();
        try{
            List<Category> list =  categoryService.list(criteria);
            CategorySimpleTreeNode rootNode = new CategorySimpleTreeNode();
            rootNode.setV("0");
            rootNode.setN("root");
            nodeMap.put(0l,rootNode);
            if(!CollectionUtils.isEmpty(list)){
                for (Category category : list){
                    if(category.isVisible()){
                        CategorySimpleTreeNode treeNode = new CategorySimpleTreeNode();
                        treeNode.setV(category.getId().toString());
                        treeNode.setN(category.getName());
                        nodeMap.put(category.getId(),treeNode);

                        if(category.getParent() == null){
                            rootNode.addChild(treeNode);
                        }else {
                            CategorySimpleTreeNode parentNode = nodeMap.get(category.getParent().getId());
                            if (category.getParent().isVisible() && parentNode != null){
                                parentNode.addChild(treeNode);
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
        }
        return nodeMap.get(0l).getS();
    }
}
